<template>
    <view class="subpage-wrap">
        <view class="select-box">
            <van-dropdown-menu>
                <van-dropdown-item :value="valueTime" :options="optionTime" />
                <van-dropdown-item :value="valueStatus" :options="optionStatus" />
            </van-dropdown-menu>
        </view>
        <view v-if="typeListData.length">
            <message-item v-for="(item,index) in typeListData" :key="index" :data="item"  :typeData="typeData"
                @clickItem="onClickItem"></message-item>
        </view>
        <view v-if="typeListData.length === 0" class="not-list">
            <u-empty mode="list" text="暂无数据">
            </u-empty>
        </view>


    </view>
</template>

<script>
import messageItem from './components/messageItem.vue';
export default {
    props: {
    },
    components: { messageItem },
    computed: {
        userInfo() {
            // const storeInfo = uni.getStorageSync('appUserInfo')
            // const { appUserInfo } = this.$store.state.workbench
            // return Object.keys(appUserInfo).length > 1 ? appUserInfo : JSON.parse(storeInfo)
            return {}
        },
        typeIrem() {
            // console.log(this.$store.state.workbench.MessageTypeItem, 'data')
            // return this.$store.state.workbench.MessageTypeItem
            return {
                "msgType": 7,
                "msgTypeName": "公告",
                "msgTitle": "员工公告",
                "sendTime": 1762830370000,
                "count": 5,
                "readCount": 6
            }
        },
    },

    data() {
        return {
            valueTime: 1,
            valueStatus: '',
            firstApp: null,

            commonHeight: this.$store.state.baseData.commonHeight,
            typeListData: [{
                "msgId": "1172854884113305600",
                "appId": "19858",
                "mobileAppId": null,
                "templateCode": "YGGG001",
                "msgTitle": "员工公告",
                "msgContent": "重要公告",
                "sendTime": 1762830370000,
                "msgStatus": true,
                "paramsJson": "{\"noticeInnerId\":\"1172854539434213376\",\"user_notice_type\":\"重要公告\",\"user_title\":\"重要公告\",\"user_notice_abstract\":\"\",\"orgId\":\"977\"}",
                "jumpUrlsJson": "{\"title\":\"员工公告\",\"web\":[\"/roc-component-workbench/#/employeeNoticeWebDetail\"],\"app\":[\"/wyt-entry-toB/index.html#/noticeDetail\"]}",
                "n": null,
                "noticeVoiceName": null
            },
            {
                "msgId": "1172854859849256960",
                "appId": "19858",
                "mobileAppId": null,
                "templateCode": "YGGG001",
                "msgTitle": "员工公告",
                "msgContent": "提示信息",
                "sendTime": 1762830367000,
                "msgStatus": false,
                "paramsJson": "{\"noticeInnerId\":\"1172854552193286144\",\"user_notice_type\":\"提示\",\"user_title\":\"提示信息\",\"user_notice_abstract\":\"\",\"orgId\":\"977\"}",
                "jumpUrlsJson": "{\"title\":\"员工公告\",\"web\":[\"/roc-component-workbench/#/employeeNoticeWebDetail\"],\"app\":[\"/wyt-entry-toB/index.html#/noticeDetail\"]}",
                "n": null,
                "noticeVoiceName": null
            },
            {
                "msgId": "1172854835610374144",
                "appId": "19858",
                "mobileAppId": null,
                "templateCode": "YGGG001",
                "msgTitle": "员工公告",
                "msgContent": "紧急公告紧急公告",
                "sendTime": 1762830362000,
                "msgStatus": false,
                "paramsJson": "{\"noticeInnerId\":\"1172854524884172800\",\"user_notice_type\":\"紧急公告\",\"user_title\":\"紧急公告紧急公告\",\"user_notice_abstract\":\"\",\"orgId\":\"977\"}",
                "jumpUrlsJson": "{\"title\":\"员工公告\",\"web\":[\"/roc-component-workbench/#/employeeNoticeWebDetail\"],\"app\":[\"/wyt-entry-toB/index.html#/noticeDetail\"]}",
                "n": null,
                "noticeVoiceName": null
            },
            {
                "msgId": "1172854349503123456",
                "appId": "19858",
                "mobileAppId": null,
                "templateCode": "YGGG001",
                "msgTitle": "员工公告",
                "msgContent": "提示信息",
                "sendTime": 1762830244000,
                "msgStatus": false,
                "paramsJson": "{\"noticeInnerId\":\"1172853853078306816\",\"user_notice_type\":\"提示\",\"user_title\":\"提示信息\",\"user_notice_abstract\":\"\",\"orgId\":\"977\"}",
                "jumpUrlsJson": "{\"title\":\"员工公告\",\"web\":[\"/roc-component-workbench/#/employeeNoticeWebDetail\"],\"app\":[\"/wyt-entry-toB/index.html#/noticeDetail\"]}",
                "n": null,
                "noticeVoiceName": null
            },
            {
                "msgId": "1172854328472883200",
                "appId": "19858",
                "mobileAppId": null,
                "templateCode": "YGGG001",
                "msgTitle": "员工公告",
                "msgContent": "重要公告",
                "sendTime": 1762830241000,
                "msgStatus": false,
                "paramsJson": "{\"noticeInnerId\":\"1172853994426351616\",\"user_notice_type\":\"重要公告\",\"user_title\":\"重要公告\",\"user_notice_abstract\":\"\",\"orgId\":\"977\"}",
                "jumpUrlsJson": "{\"title\":\"员工公告\",\"web\":[\"/roc-component-workbench/#/employeeNoticeWebDetail\"],\"app\":[\"/wyt-entry-toB/index.html#/noticeDetail\"]}",
                "n": null,
                "noticeVoiceName": null
            },
            {
                "msgId": "1172854328120561664",
                "appId": "19858",
                "mobileAppId": null,
                "templateCode": "YGGG001",
                "msgTitle": "员工公告",
                "msgContent": "紧急公告紧急公告",
                "sendTime": 1762830239000,
                "msgStatus": false,
                "paramsJson": "{\"noticeInnerId\":\"1172854207874482176\",\"user_notice_type\":\"紧急公告\",\"user_title\":\"紧急公告紧急公告\",\"user_notice_abstract\":\"\",\"orgId\":\"977\"}",
                "jumpUrlsJson": "{\"title\":\"员工公告\",\"web\":[\"/roc-component-workbench/#/employeeNoticeWebDetail\"],\"app\":[\"/wyt-entry-toB/index.html#/noticeDetail\"]}",
                "n": null,
                "noticeVoiceName": null
            }],
            typeData: {
                "msgType": 7,
                "msgTypeName": "公告",
                "msgTitle": "员工公告",
                "sendTime": 1762830370000,
                "count": 5,
                "readCount": 6
            },
            accessToken: '',
            loading: false, // van-list的加载
            finished: false, // van-list的数据是否加载完毕
            optionTime: [
                { text: '全部时间', value: 1 },
                { text: '今日', value: 2 },
                { text: '昨日', value: 3 },
                { text: '近7天', value: 4 },
                { text: '近30天', value: 5 }
            ],
            optionStatus: [
                { text: '全部状态', value: '' },
                { text: '未读', value: '0' },
                { text: '已读', value: '1' }
            ],
            pagination: {
                pageNum: 1,
                pageSize: 20,
                total: 0
            }
        }
    },
    async onLoad(options) {

        //  const data = JSON.parse(decodeURIComponent(options.data));
        // await this.init()
        // this.getList()
        console.log(options, 'data')
        console.log(this.commonHeight, 'typecommon')
        //  console.log(JSON.parse(options.data), 'data2')
        // console.log(decodeURIComponent(options.data), 'data3')
        // document.title = data.msgTypeName || ''
    },
    methods: {
        async getList() {
            if (!this.accessToken) {
                let appOrgInfo = uni.getStorageSync('appOrgInfo')
                if (!appOrgInfo) return
                const { memberId, orgId } = JSON.parse(appOrgInfo)
                let res = await this.$Geting(this.$api.getTokenByAppIdMemberIdOrgId, { appId: this.firstApp.relationAppId, orgId, memberId })
                this.accessToken = res.data.accessToken
            }

            let sendTimeStart = ''
            let sendTimeEnd = ''
            if (this.valueTime === 1) { // 全部时间
            } else if (this.valueTime === 2) { // 今日
                sendTimeStart = dayjs().startOf('day').valueOf()
                sendTimeEnd = dayjs().endOf('day').valueOf()
            } else if (this.valueTime === 3) { // 昨日
                sendTimeStart = dayjs().add(-1, 'day').startOf('day').valueOf()
                sendTimeEnd = dayjs().add(-1, 'day').endOf('day').valueOf()
            } else if (this.valueTime === 4) { // 近7天
                sendTimeStart = dayjs().add(-6, 'day').startOf('day').valueOf()
                sendTimeEnd = dayjs().add(-6, 'day').endOf('day').valueOf()
            } else if (this.valueTime === 5) { // 近30天
                sendTimeStart = dayjs().add(-29, 'day').startOf('day').valueOf()
                sendTimeEnd = dayjs().add(-29, 'day').endOf('day').valueOf()
            }
            let query = {
                userId: this.userInfo.memberId,
                msgStatus: ['0', '1'].includes(this.valueStatus) ? this.valueStatus * 1 : '',
                msgType: this.typeData.msgType,
                sendTimeEnd: sendTimeEnd,
                terminal: 1,
                sendTimeStart: sendTimeStart
            }
            let postData = {
                pageNum: this.pagination.pageNum,
                pageSize: this.pagination.pageSize,
                query
            }
            // const { data } = await axios.post(getBaseURL() + this.$api.Messagedetailedquerylist, postData, {
            //     headers: {'X-Access-Source': 'roc', 'X-Access-Token': this.accessToken}
            // })
            const { data } = this.$Geting(this.$api.Messagedetailedquerylist, postData, { 'X-Access-Source': 'roc', 'X-Access-Token': this.accessToken })
            // this.loading = false
            let code = data.code
            if (code === '0') {
                if (this.pagination.pageNum === 1) { // 如果是第一页，则清空数据
                    this.listData = []
                }
                let list = data.data.list || []
                // 将json数据提前转换，方便模板里面直接访问数据或判断
                const newList = list.map(x => {
                    let jumpUrlsJson = x.jumpUrlsJson;
                    if (jumpUrlsJson) {
                        x.jumpUrlsJson = JSON.parse(x.jumpUrlsJson);
                    }
                    let paramsJson = x.paramsJson;
                    if (paramsJson) {
                        x.paramsJson = JSON.parse(x.paramsJson);
                    }
                    return x;
                });
                this.listData = this.listData.concat(newList)
                if (data.data.isLastPage) {
                    this.finished = true
                }
            }
        },
        init() {
            let storeApps = this.$store.state.workbench.appList
            if (storeApps.length) {
                let firstApp = null
                for (let i = 0; i < storeApps.length; i++) {
                    let apps = storeApps[i].apps
                    if (apps.length) {
                        firstApp = apps[0]
                    }
                    if (firstApp) {
                        break
                    }
                }
                this.firstApp = firstApp
            }

            // let query = this.$route.query
            // this.typeData = { ...query }
        },
        handleAssetsMsg(msgItem) {
            // 获取消息参数
            const paramsJson = msgItem.paramsJson || {};

            // 检查是否有详情地址
            if (!paramsJson.url) {
                uni.showToast({
                    title: '消息中未提供详情地址',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            // 获取token（小程序使用storageSync）
            const token = uni.getStorageSync('XUserToken') || '';
            if (!token) {
                uni.showToast({
                    title: '未获取到token',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            // 处理原始URL和参数编码
            let url = paramsJson.url;
            // 判断URL中是否已有问号（用于拼接参数）
            const andS = url.includes('?') ? '&' : '?';

            // 如果已有参数，对原有参数值进行编码
            if (andS === '&') {
                const [baseUrl, queryStr] = url.split('?');
                if (queryStr) {
                    const queryParams = queryStr.split('&').map(param => {
                        const [key, value] = param.split('=');
                        // 只编码有值的参数（避免空值报错）
                        return value ? `${key}=${encodeURIComponent(value)}` : key;
                    });
                    url = `${baseUrl}?${queryParams.join('&')}`;
                }
            }

            // 拼接token参数
            const webViewUrl = `${url}${andS}token=${token}`;
            console.log('跳转的url地址', webViewUrl);

            // 标记消息为已读
            this.markstatusmethod(msgItem.msgId);
            msgItem.msgStatus = true;

            // 小程序中使用web-view承载H5页面（需创建专用页面）
            // uni.navigateTo({
            //     url: `/pages/webView/webView?url=${encodeURIComponent(webViewUrl)}`
            // });
        },
        async onClickItem(its) {
            console.log('你点击的是', its)
            if (its.msgTitle && its.msgTitle === '跟进人离职') {
                return;
            }
            if (its.templateCode && its.templateCode.indexOf('GOOD_ORDER') > -1) {
                return;
            }

            let msgType = Number(this.typeData.msgType);

            // 资产管理消息处理
            if (msgType === 9) {
                this.handleAssetsMsg(its);
                return;
            }

            // 蓝凌OA消息处理
            if (msgType === 19) {
                if (its.templateCode === 'JeezOA') {
                    this.handleJeezOAMsg(its);
                    return;
                }
                this.handleOAMsg(its);
                return;
            }

            // 处理跳转参数
            let jumplink = its.jumpUrlsJson;
            let cshu = its.paramsJson || {};
            let preserva = '';
            let paramKeys = Object.keys(cshu);

            // 拼接参数（排除url字段）
            paramKeys.forEach((key, i) => {
                if (key !== 'url') {
                    preserva += `${key}=${encodeURIComponent(cshu[key])}${paramKeys.length === i + 1 ? '' : '&'}`;
                }
            });

            // 获取用户信息
            const { orgId, memberId } = this.userInfo;
            const params = {
                orgId,
                memberId,
                appId: its.appId || ''
            };

            // 确定跳转基础路径
            let preUrl = '';
            if (jumplink && jumplink.app && jumplink.app.length) {
                preUrl = jumplink.app[0];
            } else if (jumplink && jumplink.applet && jumplink.applet.length) {
                preUrl = jumplink.applet[0];
            }

            // 跳转地址为空处理
            if (!preUrl) {
                // 标记已读
                if (!its.msgStatus) {
                    its.msgStatus = true;
                    this.markstatusmethod(its.msgId);
                }
                uni.showToast({
                    title: '跳转地址为空',
                    icon: 'none'
                });
                return;
            }

            // 标记消息为已读
            this.markstatusmethod(its.msgId);
            its.msgStatus = true;

            // 通知公告类型（直接跳转内部页面）
            if (msgType === 7) {
                uni.navigateTo({
                    url: `/pages/noticeDetail/noticeDetail?id=${cshu.noticeInnerId}`
                });
                return;
            }

            // 其他类型消息（处理H5跳转）
            try {
                // 获取token（小程序使用storageSync）
                const token = uni.getStorageSync('XUserToken');
                if (!token) {
                    uni.showToast({
                        title: '未获取到token',
                        icon: 'none'
                    });
                    return;
                }

                // 调用接口获取code
                const codeResult = await this.$http.get(this.$api.getAppCode, params);
                if (!codeResult.data) {
                    uni.showToast({
                        title: '获取code失败',
                        icon: 'none'
                    });
                    return;
                }

                // 处理URL映射
                const matchArr = preUrl.match(/^\/(roc-[^/]+-h5)\//);
                if (!matchArr || matchArr.length < 2) {
                    uni.showToast({
                        title: 'app映射的地址未找到',
                        icon: 'none'
                    });
                    return;
                }

                const mapUrl = project[matchArr[1]]; // 假设project是全局配置的映射表
                if (!mapUrl) {
                    uni.showToast({
                        title: `${matchArr[1]}映射的地址未找到`,
                        icon: 'none'
                    });
                    return;
                }

                // 构建完整web-view URL
                let webViewUrl = preUrl.replace(/^\/(roc-[^/]+-h5)\//, `/${mapUrl}/`) +
                    `?code=${codeResult.data}&XUserToken=${token}&${preserva}`;

                // 补全index.html#路径
                if (!/index.html#/.test(webViewUrl)) {
                    webViewUrl = webViewUrl.replace('/#/', '/index.html#/');
                }

                // 跳转web-view页面（小程序需用专用页面承载H5）
                uni.navigateTo({
                    url: `/pages/webView/webView?url=${encodeURIComponent(webViewUrl)}`
                });

            } catch (error) {
                console.error('跳转异常:', error);
                uni.showToast({
                    title: '跳转失败，请重试',
                    icon: 'none'
                });
            }
        },
        // 全部标记为已读
        async markstatusmethod(msgId) {
            let postData = {
                msgType: this.typeData.msgType,
                userId: this.userInfo.memberId,
                terminal: 1
            }
            if (msgId) {
                postData.msgId = msgId
            }
            // const res = await axios.post(getBaseURL() + this.$api.Markreadinterface, postData, { headers: { 'X-Access-Source': 'roc', 'X-Access-Token': this.accessToken } });
            const res = this.$Posting(this.$api.Markreadinterface, postData, { 'X-Access-Source': 'roc', 'X-Access-Token': this.accessToken })
            this.$store.dispatch('getMessageTypeList') // 更新待办消息列表数据
            // if (res.data && !msgId) {
            //     Toast('全部标记已读')
            //     this.reloadData()
            // }
        },
    },

}
</script>


<style lang="scss" scoped>
.subpage-wrap {
    // position: absolute;
    // left: 0;
    // top: 170rpx;
    // right: 0;
    // height: calc(100vh - 170px);
    width: 100vw;
    display: flex;
    flex-direction: column;
    background-color: #fff;



}

.not-list {
    position: fixed;
    top: 40%;
    left: 50%;
    transform: translateX(-50%);
}
</style>